package com.springdatecrm.web.controller;

import com.springdatecrm.web.entity.Role;
import com.springdatecrm.web.entity.User;
import com.springdatecrm.web.service.RoleService;
import com.springdatecrm.web.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @RequestMapping(value = "/dologin")
    public String dologin(String usrName, String usrPassword, HttpServletRequest request, Map<String,Object>map,
            HttpSession session){
//        User user = userService.login(usrName,usrPassword);
//        if (user!=null) {
//            request.getSession().setAttribute("user",user);
//            return "main";
//        } else {
//            request.setAttribute("message","登录失败，用户名或密码错误！");
//            return "login";
//        }
        User user = null;

        try {
            //此处不再处理登录，由shiro进行处理
            AuthenticationToken token = new UsernamePasswordToken(usrName,usrPassword);
            SecurityUtils.getSubject().login(token);        //调用Shiro认证
            user = (User)SecurityUtils.getSubject().getPrincipal();

            //注意此处的 session.setAttribute 中 key 的值
            //需要和 AuthorizationInterceptor 拦截器 session 的 key 一直
            session.setAttribute("user",user);
        } catch (Exception e) {
            map.put("message",e.getMessage());
            return "login";
        }

        return "main";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        //删除session
        session.removeAttribute("user");

        //调用登出方法
        SecurityUtils.getSubject().logout();

        return "login";
    }

    @RequestMapping(value = "/user/list")
    public String list(String usrName, Model model,
                       @RequestParam(required = false,defaultValue = "0")Long roleId,
                       @RequestParam(required = false,defaultValue = "1")int pageIndex) {

        Sort sort = new Sort(Sort.Direction.ASC,"usrId");
        //控制分页的辅助类，可以设置页码(从0开始)
        Pageable pageable = PageRequest.of(pageIndex-1,5,sort);
        Page<User> userPager = userService.findUsers(usrName,roleId,pageable);
        List<User> list  = userService.findAllUsers(usrName,roleId);
        List<Role> roles = roleService.findAllRoles();
        model.addAttribute("userPager",userPager);
        model.addAttribute("usrName",usrName);
        model.addAttribute("roles",roles);
        model.addAttribute("roleId",roleId);
        model.addAttribute("users",list);

        return "user/list";
    }


    @RequestMapping(value = "/user/add")
    public String add(Model model) {
        List<Role> list = roleService.findAllRoles();
        model.addAttribute("roles",list);
        return "user/add";
    }

    @RequestMapping(value = "/user/save",method = RequestMethod.POST)
    public String save(User user) {
        userService.save(user);
        return "redirect:/user/list";
    }

    @RequestMapping(value = "/user/edit")
    public String edit(Model model,Long usrId) {
        User user = userService.getUser(usrId);
        List<Role> list = roleService.findAllRoles();
        model.addAttribute("user",user);
        model.addAttribute("roles",list);
        return "user/edit";
    }

    @RequestMapping(value = "/user/editSave",method = RequestMethod.POST)
    public String editModify(User user) {
        User user1 = new User();
        user1.setUsrName(user.getUsrName());
        user1.setUsrPassword(user.getUsrPassword());
        user1.setRole(user.getRole());
        user1.setUsrFlag(user.getUsrFlag());
        user1.setUsrId(user.getUsrId());
        userService.save(user1);
        return "redirect:/user/list";
    }


    @RequestMapping(value = "/user/del",method = RequestMethod.GET)
    @ResponseBody
    public Object del(Long usrId) {
        userService.deleteUser(usrId);
        Map<Object,Object> map = new HashMap<Object, Object>();
        map.put("delResult","true");
        return map;
    }

}
